package com.example.JPetStore.dao;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.JPetStore.Common;
import com.example.JPetStore.domain.User;
import com.example.JPetStore.mappers.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.*;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Service
public class UserDao {

    @Autowired
    private  UserMapper userMapper;


    public User queryUser(String userId){
        User user=userMapper.selectById(userId);
        return user;
    }

    public  User queryUser1(String nickName){
        User user=userMapper.selectOne(new QueryWrapper<User>().eq("nick_name",nickName));

        return user;
    }
    public User registerUser(User user) {
        user.setPassword(Common.md5(user.getPassword()));
        userMapper.insert(user);
        return user;
    }
    public static String getRandCode(){
        String s;

        char[] allChars=("1234567890abcdefghijklmnopqrstuvwxyz").toCharArray();

        for(int i=0;i<1000;i++){
            int j1=(int)(Math.random()*allChars.length);
            int j2=(int)(Math.random()*allChars.length);
            char tem=allChars[j1];
            allChars[j1]=allChars[j2];
            allChars[j2]=tem;
        }
        s=new String();

        for(int i=0;i<4;i++){
            s+=allChars[i];
        }

        return s;
    }
    public void updateLoginTimestamp(User user){
        User user2=new User();
        user2.setUserId(user.getUserId());
        user2.setLastLoginTimestamp(LocalDateTime.now());
        userMapper.updateById(user2);
    }

    public  void editInfo(String userId, String nickName) {

        User user=new User();
        user.setUserId(userId);
        user.setNickName(nickName);

        userMapper.updateById(user);
    }

    public void editPassword(String userId, String newPassword) {

        User user=new User();
        user.setUserId(userId);
        user.setPassword(newPassword);


        userMapper.updateById(user);
    }
}
